<?php
/**
 * 缓存管理控制器
 * 作者: 王勇程 (laughskydragon@qq.com)
 */

namespace app\admin\controller;

use app\admin\controller\AdminBase;

class Cache extends AdminBase
{
    /**
     * 缓存管理首页
     */
    public function index()
    {
        // 获取缓存统计信息
        $stats = \app\common\service\PriceCache::getCacheStats();
        
        $this->assign('stats', $stats);
        
        return $this->fetch();
    }
    
    /**
     * 清理过期缓存
     */
    public function cleanExpired()
    {
        $cleanedCount = \app\common\service\PriceCache::cleanExpiredCache();
        
        $this->jump([RESULT_SUCCESS, '清理完成，共清理 ' . $cleanedCount . ' 条过期缓存', url('index')]);
    }
    
    /**
     * 清理所有价格缓存
     */
    public function clearPriceCache()
    {
        \app\common\service\PriceCache::clearAllPriceCache();
        
        $this->jump([RESULT_SUCCESS, '价格缓存已清理', url('index')]);
    }
    
    /**
     * 清理指定商品缓存
     */
    public function clearProductCache()
    {
        $productId = $this->request->param('product_id', 0, 'intval');
        
        if (!$productId) {
            $this->jump([RESULT_ERROR, '商品ID不能为空']);
        }
        
        \app\common\service\PriceCache::clearProductPrice($productId);
        
        $this->jump([RESULT_SUCCESS, '商品缓存已清理', url('index')]);
    }
    
    /**
     * 清理系统缓存
     */
    public function clearSystemCache()
    {
        // 清理ThinkPHP缓存
        \think\facade\Cache::clear();
        
        $this->jump([RESULT_SUCCESS, '系统缓存已清理', url('index')]);
    }
    
    /**
     * 获取缓存详情
     */
    public function detail()
    {
        $type = $this->request->param('type', '');
        
        $data = [];
        
        switch ($type) {
            case 'price':
                $data = \app\common\service\PriceCache::getCacheStats();
                break;
            case 'system':
                // 获取系统缓存信息
                $data = [
                    'cache_type' => config('cache.default'),
                    'cache_config' => config('cache.stores.' . config('cache.default'))
                ];
                break;
            default:
                $this->jump([RESULT_ERROR, '缓存类型错误']);
        }
        
        $this->assign('data', $data);
        $this->assign('type', $type);
        
        return $this->fetch();
    }
    
    /**
     * 缓存清理
     */
    public function clear()
    {
        $type = $this->request->param('type', 'all');
        
        switch ($type) {
            case 'price':
                \app\common\service\PriceCache::clearAllPriceCache();
                $message = '价格缓存已清理';
                break;
            case 'system':
                \think\facade\Cache::clear();
                $message = '系统缓存已清理';
                break;
            case 'expired':
                $cleanedCount = \app\common\service\PriceCache::cleanExpiredCache();
                $message = '过期缓存已清理，共清理 ' . $cleanedCount . ' 条';
                break;
            case 'all':
            default:
                \think\facade\Cache::clear();
                \app\common\service\PriceCache::clearAllPriceCache();
                $message = '所有缓存已清理';
                break;
        }
        
        $this->jump([RESULT_SUCCESS, $message, url('index')]);
    }
    
    /**
     * 缓存统计
     */
    public function stats()
    {
        // 获取价格缓存统计
        $priceStats = \app\common\service\PriceCache::getCacheStats();
        
        // 获取系统缓存统计
        $systemStats = [
            'cache_type' => config('cache.default'),
            'cache_config' => config('cache.stores.' . config('cache.default')),
            'memory_usage' => function_exists('memory_get_usage') ? memory_get_usage(true) : 0,
            'memory_peak' => function_exists('memory_get_peak_usage') ? memory_get_peak_usage(true) : 0
        ];
        
        $this->assign('priceStats', $priceStats);
        $this->assign('systemStats', $systemStats);
        
        return $this->fetch();
    }
    
    /**
     * 缓存配置
     */
    public function config()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            
            // 这里可以添加缓存配置的保存逻辑
            // 由于OneBase的配置管理，这里主要是展示配置信息
            
            $this->jump([RESULT_SUCCESS, '缓存配置已更新', url('config')]);
        }
        
        // 获取当前缓存配置
        $config = [
            'cache_type' => config('cache.default'),
            'cache_prefix' => config('cache.prefix', 'yyjd_'),
            'cache_expire' => config('cache.expire', 3600),
            'price_cache_enable' => true,
            'price_cache_time' => 1800,
            'price_cache_auto_refresh' => true,
            'auto_clean_enable' => true,
            'clean_interval' => 3600,
            'max_cache_size' => 100
        ];
        
        $this->assign('config', $config);
        
        return $this->fetch();
    }
    
    /**
     * 缓存监控
     */
    public function monitor()
    {
        // 获取实时缓存状态
        $monitorData = [
            'price_cache' => \app\common\service\PriceCache::getCacheStats(),
            'system_info' => [
                'php_version' => PHP_VERSION,
                'memory_limit' => ini_get('memory_limit'),
                'max_execution_time' => ini_get('max_execution_time'),
                'current_memory' => function_exists('memory_get_usage') ? memory_get_usage(true) : 0
            ],
            'cache_status' => [
                'type' => config('cache.default'),
                'available' => true // 可以添加更详细的检测逻辑
            ]
        ];
        
        $this->assign('monitorData', $monitorData);
        
        return $this->fetch();
    }
    
    /**
     * 缓存预热
     */
    public function warmup()
    {
        // 缓存预热逻辑
        $warmedCount = 0;
        
        try {
            // 这里可以添加具体的预热逻辑
            // 比如预加载热门商品的价格缓存等
            
            $message = '缓存预热完成，预热 ' . $warmedCount . ' 项缓存';
            
            $this->jump([RESULT_SUCCESS, $message, url('index')]);

        } catch (\Exception $e) {
            $errorMessage = '缓存预热失败：' . $e->getMessage();
            
            $this->jump([RESULT_ERROR, $errorMessage]);
        }
    }
}